<?php
/**
 * PHP Framework ICQ client search HTTP web service reference
 *
 * Implemented patterns: Proxy
 *
 * @author Andrew <andrew@vitche.com>
 * @author Frozen Rain <frozenrain@mail.ru>
 **/
class IcqSearchHTTPWebServiceReference extends HTTPWebServiceReference {

    /**
     * Constructs a new instance of the ICQ search web service reference
     **/
    public function __construct() {
        parent::__construct("http://people.icq.com/people/include/xhr.php");
    }

    /**
     * Performs ICQ users search
     * @param Array $arguments A list of arguments for the method being called
     **/
    public function search($arguments) {

        // Locals
        $matches = array();
        $results = array();

        // Execute the HTTP call
        $response = $this->execute(null, $arguments);

        // Parse response
        $document = new simple_html_dom($response);
        $document->set_callback('IcqSearchHTTPWebServiceReference::onFilterData');

        // Find all user entries
        $response = $document->find(".ubb");
        foreach ($response as $account) {

            $IcqAccount = new IcqAccount();

            // Parse user image and UIN
            $ubb1 = $account->find(".ubb-1 a img", 0);
            $ubb1Src = $ubb1->getAttribute("src");
            $ubb1Alt = $ubb1->getAttribute("alt");

            preg_match('/([0-9]{5,10})/', $ubb1Alt, $matches);

            // Parse user name
            $ubb2 = $account->find(".ubb-2 a", 0);
            $ubb2Content = $ubb2->innertext();

            $IcqAccount->uin = trim($matches[1]);
            $IcqAccount->name = trim($ubb2Content);
            $IcqAccount->imageUrl = trim($ubb1Src);
            $results[] = $IcqAccount;
        }

        // Results
        return $results;
    }

    /**
     * Performs ICQ users search recurrently loading all user accounts
     * @param Array $arguments A list of arguments for the method being called
     **/
    public function recurrentSearch($arguments) {

        $results = array();

        $i = 0;
        while(true) {

            // Handle iterator state
            $arguments['page'] = $i++;

            // Perform one search call
            $portion = $this->search($arguments);

            // Stop loading if last request returned no results
            if (0 == count($portion)) {
                break;
            }

            // Keep portion's results
            $results = array_merge($results, $portion);
        }

        return $results;
    }

    public static function onFilterData($node) {
    }
}
?>